import React, {Fragment} from "react";
import View from "../base/View";
import defaultData from "./data";
import {WeaInput, WeaLocaleProvider, WeaSelect} from "ecCom";
import {OTHER} from "../../../../../constants/form";

const getLabel = WeaLocaleProvider.getLabel;

export default class ComboboxView extends View {
  state = {
    otherValue: ''
  };

  formatValue(value) {
    if(value.target) {
      value = value.target.value;
    }

    return [{
      key: value,
      value: OTHER === value ? this.state.otherValue : ''
    }];
  }

  handleOtherValueChange = otherValue => {
    const { value } = this.props;
    const hasOtherSelected = value[0] && OTHER === value[0].key;

    this.setState({ otherValue });

    if(hasOtherSelected) {
      this.props.onChange([{
        key: OTHER,
        value: otherValue
      }]);
    }
  }

  renderOtherOption() {
    const { value } = this.props;
    const { otherValue } = this.state;
    const [ val = {} ] = value;

    return (
      <Fragment>
        {OTHER !== val.key ? null :
          <WeaInput
            value={otherValue}
            style={{ paddingTop: 5 }}
            onChange={this.handleOtherValueChange}
          />
        }
      </Fragment>
    );
  }

  renderForPC(data, value) {
    const [val = {}] = value;

    return (
      <Fragment>
        <WeaSelect
          style={{ minWidth: 166 }}
          value={val.key}
          options={data.options}
          onChange={this.handleValueChange}
        />
        {this.renderOtherOption()}
      </Fragment>
    );
  }

  renderForMobile(data) {
    return (
      <div className='wea-edc-select-container'>
        <select onChange={this.handleValueChange} >
          <option value=''>{getLabel('502500','请选择')}</option>
          {data.options.map(opt => (
            <option selected={opt.selected} key={opt.key} value={opt.key}>{opt.showname}</option>
          ))}
        </select>
        {this.renderOtherOption()}
      </div>
    );
  }

  renderForReadonly(data, value) {
    let options = {};
    data.options.map(({key, showname}) => {
      options[key] = showname;
    });

    return (
      <ul>
        {value.map(({ key, value }) => (
          <li>{value || options[key]}</li>
        ))}
      </ul>
    )
  }
}

ComboboxView.defaultProps = {
  data: defaultData,
};